package springboot.example.springboot;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadAndWriteLock {

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    new TestStr().write();
                    new TestStr().read();
                    new TestStr().write();
                    new TestStr().read();
                    new TestStr().write();
                    new TestStr().read();
                }
            }).start();
        }

    }


}

class TestStr {

    static int count = 1;
    ReadWriteLock lock = new ReentrantReadWriteLock();

    public void write(){
        lock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"write start");

        for (int i = 0 ; i< 3;i++){
            count ++;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(count);
        System.out.println(Thread.currentThread().getName()+"write end");
        lock.writeLock().unlock();
    }

    public void read(){
        lock.readLock().lock();
        System.out.println(Thread.currentThread().getName()+"read start");
        System.out.println(count);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"read end");
        lock.readLock().unlock();
    }


}
